package models.base;

import com.tom.basic.serialize.json.GsonField;
import com.tom.basic.serialize.json.GsonSkip;
import org.apache.commons.lang.time.DateFormatUtils;
import play.db.jpa.Model;
import utils.BizConstants;
import utils.OrderMetaUtils;

import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.util.Date;
import java.util.Map;

@MappedSuperclass
public class BaseModel extends Model {

    public Date gmtCreate;

    public Date gmtModify;

    public int isDelete;

    @Transient
    @GsonSkip
    public transient boolean timeSwitch = true;

    @GsonField(name = "gmtCreateShow")
    public String getGmtCreateShow() {
        if (!timeSwitch) {
            return null;
        }
        return DateFormatUtils.format(gmtCreate, BizConstants.TIME_SECOND_FORMATE);
    }

    @GsonField(name = "gmtCreateShowShort")
    public String getGmtCreateShowShort() {
        if (!timeSwitch) {
            return null;
        }
        return DateFormatUtils.format(gmtModify, BizConstants.TIME_SECOND_FORMATE);
    }


    /**
     * 扩展信息,格式:key1:v1;key2:v2;key3:v3;
     */
    public String orderMeta;

    @Transient
    @GsonSkip
    private transient OrderMetaUtils orderMetaUtils = new OrderMetaUtils();

    public void addMeta(String meta, Integer value) {
        addMeta(meta, value.toString());
    }

    public void addMeta(String meta, Long value) {
        if (value == null) {
            return;
        }
        addMeta(meta, value.toString());
    }

    public void addMeta(String meta, String value) {
        this.orderMeta = orderMetaUtils.addMeta(orderMeta, meta, value);
    }

    public void removeMeta(String meta) {
        this.orderMeta = orderMetaUtils.removeMeta(orderMeta, meta);
    }

    public Long getMetaLongVal(String meta) {
        return orderMetaUtils.getMetaLongVal(orderMeta, meta);
    }


    public String getMetaValue(String meta) {
        return orderMetaUtils.getMetaValue(orderMeta, meta);
    }

    public Map<String, String> getOrderMetaMap() {
        return orderMetaUtils.getOrderMetaMap(orderMeta);
    }


    public BaseModel(Date gmtCreate, Date gmtModify, int isDelete) {
        super();
        this.gmtCreate = gmtCreate;
        this.gmtModify = gmtModify;
        this.isDelete = isDelete;
    }

    public BaseModel(boolean timeSwitch) {
        super();
        this.timeSwitch = timeSwitch;
    }

    public BaseModel() {
        this(new Date(), new Date(), 0);
    }

    public boolean isAlreadyDelete() {
        return isDelete == 1;
    }

}
